<template>
  <div class="gesture-navigation">
    <!-- 手势轨迹显示 -->
    <svg 
      v-if="isGesturing"
      class="gesture-trail"
      :width="windowSize.width"
      :height="windowSize.height"
    >
      <polyline
        :points="trailPoints"
        fill="none"
        stroke="#409eff"
        stroke-width="3"
        stroke-linecap="round"
        stroke-linejoin="round"
        opacity="0.6"
      />
    </svg>

    <!-- 手势提示 -->
    <transition name="fade">
      <div 
        v-if="gestureHint" 
        class="gesture-hint"
        :style="{ left: hintPosition.x + 'px', top: hintPosition.y + 'px' }"
      >
        <div class="hint-icon">
          <el-icon><component :is="gestureHint.icon" /></el-icon>
        </div>
        <div class="hint-text">{{ gestureHint.text }}</div>
      </div>
    </transition>

    <!-- 手势设置按钮 -->
    <el-button 
      class="gesture-settings-btn"
      size="small"
      circle
      @click="showSettings = true"
    >
      <el-icon><MagicStick /></el-icon>
    </el-button>

    <!-- 手势配置对话框 -->
    <el-dialog
      v-model="showSettings"
      title="鼠标手势设置"
      width="700px"
    >
      <el-alert 
        title="如何使用鼠标手势" 
        type="info" 
        :closable="false"
        style="margin-bottom: 20px"
      >
        <div>按住鼠标<strong>右键</strong>并移动鼠标绘制手势，松开后执行对应操作</div>
      </el-alert>

      <div class="gestures-list">
        <h4>可用手势列表</h4>
        <el-table :data="gestureConfig" border>
          <el-table-column label="手势轨迹" width="150">
            <template #default="{ row }">
              <div class="gesture-preview">
                <svg width="100" height="60" viewBox="0 0 100 60">
                  <path 
                    :d="getGesturePath(row.pattern)" 
                    fill="none" 
                    stroke="#409eff" 
                    stroke-width="2"
                  />
                </svg>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="pattern" label="手势代码" width="100" />
          <el-table-column prop="description" label="操作说明" />
          <el-table-column label="启用">
            <template #default="{ row }">
              <el-switch v-model="row.enabled" />
            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <el-button @click="showSettings = false">取消</el-button>
        <el-button type="primary" @click="saveGestureSettings">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { MagicStick } from '@element-plus/icons-vue'

const router = useRouter()

// 窗口大小
const windowSize = reactive({
  width: window.innerWidth,
  height: window.innerHeight
})

// 手势状态
const isGesturing = ref(false)
const gesturePoints = ref([])
const gestureHint = ref(null)
const hintPosition = reactive({ x: 0, y: 0 })
const showSettings = ref(false)

// 手势配置
const gestureConfig = ref([
  { 
    pattern: 'L', 
    description: '返回上一页', 
    action: 'back', 
    icon: 'Back',
    enabled: true 
  },
  { 
    pattern: 'R', 
    description: '前进下一页', 
    action: 'forward', 
    icon: 'Right',
    enabled: true 
  },
  { 
    pattern: 'U', 
    description: '返回首页', 
    action: 'home', 
    icon: 'HomeFilled',
    enabled: true 
  },
  { 
    pattern: 'D', 
    description: '刷新页面', 
    action: 'refresh', 
    icon: 'Refresh',
    enabled: true 
  },
  { 
    pattern: 'RD', 
    description: '打开低代码平台', 
    action: 'lowcode', 
    icon: 'MagicStick',
    enabled: true 
  },
  { 
    pattern: 'LD', 
    description: '打开合同管理', 
    action: 'contract', 
    icon: 'Document',
    enabled: true 
  },
  { 
    pattern: 'UD', 
    description: '打开搜索', 
    action: 'search', 
    icon: 'Search',
    enabled: true 
  }
])

// 轨迹点（用于SVG绘制）
const trailPoints = computed(() => {
  return gesturePoints.value.map(p => `${p.x},${p.y}`).join(' ')
})

// 鼠标按下
const handleMouseDown = (event) => {
  if (event.button === 2) { // 右键
    event.preventDefault()
    isGesturing.value = true
    gesturePoints.value = [{ x: event.clientX, y: event.clientY }]
  }
}

// 鼠标移动
const handleMouseMove = (event) => {
  if (isGesturing.value) {
    event.preventDefault()
    gesturePoints.value.push({ x: event.clientX, y: event.clientY })
    
    // 实时识别手势
    const pattern = recognizeGesture(gesturePoints.value)
    if (pattern) {
      const gesture = gestureConfig.value.find(g => g.pattern === pattern && g.enabled)
      if (gesture) {
        gestureHint.value = {
          text: gesture.description,
          icon: gesture.icon
        }
        const lastPoint = gesturePoints.value[gesturePoints.value.length - 1]
        hintPosition.x = lastPoint.x + 20
        hintPosition.y = lastPoint.y - 40
      }
    }
  }
}

// 鼠标释放
const handleMouseUp = (event) => {
  if (isGesturing.value) {
    event.preventDefault()
    
    // 识别完整手势
    const pattern = recognizeGesture(gesturePoints.value)
    if (pattern) {
      executeGesture(pattern)
    }
    
    // 重置状态
    isGesturing.value = false
    gesturePoints.value = []
    gestureHint.value = null
  }
}

// 识别手势
const recognizeGesture = (points) => {
  if (points.length < 10) return null
  
  const start = points[0]
  const end = points[points.length - 1]
  const mid = points[Math.floor(points.length / 2)]
  
  const dx = end.x - start.x
  const dy = end.y - start.y
  const distance = Math.sqrt(dx * dx + dy * dy)
  
  if (distance < 50) return null
  
  // 简单的方向识别
  const angle = Math.atan2(dy, dx) * 180 / Math.PI
  
  // 单向手势
  if (angle > -45 && angle <= 45) return 'R' // 右
  if (angle > 45 && angle <= 135) return 'D' // 下
  if (angle > 135 || angle <= -135) return 'L' // 左
  if (angle > -135 && angle <= -45) return 'U' // 上
  
  // 组合手势（简化版）
  const midDx = mid.x - start.x
  const midDy = mid.y - start.y
  
  if (midDx > 30 && dy > 30) return 'RD' // 右下
  if (midDx < -30 && dy > 30) return 'LD' // 左下
  if (midDx > 30 && dy < -30) return 'RU' // 右上
  if (midDx < -30 && dy < -30) return 'LU' // 左上
  if (dy < -30 && end.y > start.y) return 'UD' // 上下
  
  return null
}

// 执行手势
const executeGesture = (pattern) => {
  const gesture = gestureConfig.value.find(g => g.pattern === pattern && g.enabled)
  if (!gesture) return
  
  switch (gesture.action) {
    case 'back':
      router.back()
      ElMessage.success('返回上一页')
      break
    case 'forward':
      router.forward()
      ElMessage.success('前进下一页')
      break
    case 'home':
      router.push('/dashboard')
      ElMessage.success('返回首页')
      break
    case 'refresh':
      location.reload()
      break
    case 'lowcode':
      router.push('/lowcode')
      ElMessage.success('打开低代码平台')
      break
    case 'contract':
      router.push('/contract/list')
      ElMessage.success('打开合同管理')
      break
    case 'search':
      // 触发搜索
      ElMessage.success('打开搜索')
      break
  }
}

// 获取手势路径（用于预览）
const getGesturePath = (pattern) => {
  const paths = {
    'L': 'M 80 30 L 20 30',
    'R': 'M 20 30 L 80 30',
    'U': 'M 50 50 L 50 10',
    'D': 'M 50 10 L 50 50',
    'RD': 'M 20 10 L 80 50',
    'LD': 'M 80 10 L 20 50',
    'RU': 'M 20 50 L 80 10',
    'LU': 'M 80 50 L 20 10',
    'UD': 'M 50 50 L 50 10 L 50 50'
  }
  return paths[pattern] || 'M 0 0'
}

// 保存设置
const saveGestureSettings = () => {
  showSettings.value = false
  ElMessage.success('手势设置已保存')
}

// 禁用右键菜单
const handleContextMenu = (event) => {
  if (isGesturing.value) {
    event.preventDefault()
  }
}

// 窗口大小变化
const handleResize = () => {
  windowSize.width = window.innerWidth
  windowSize.height = window.innerHeight
}

onMounted(() => {
  document.addEventListener('mousedown', handleMouseDown)
  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', handleMouseUp)
  document.addEventListener('contextmenu', handleContextMenu)
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  document.removeEventListener('mousedown', handleMouseDown)
  document.removeEventListener('mousemove', handleMouseMove)
  document.removeEventListener('mouseup', handleMouseUp)
  document.removeEventListener('contextmenu', handleContextMenu)
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.gesture-navigation {
  position: relative;
}

.gesture-trail {
  position: fixed;
  top: 0;
  left: 0;
  pointer-events: none;
  z-index: 9999;
}

.gesture-hint {
  position: fixed;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: rgba(64, 158, 255, 0.95);
  color: white;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  box-shadow: 0 4px 12px rgba(0,0,0,0.2);
  pointer-events: none;
  z-index: 10000;
}

.hint-icon {
  font-size: 18px;
}

.gesture-settings-btn {
  position: fixed;
  right: 30px;
  bottom: 180px;
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
  z-index: 1000;
}

.gestures-list h4 {
  margin: 0 0 15px 0;
  color: #303133;
}

.gesture-preview {
  display: flex;
  justify-content: center;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>

